<?php
/**
 * wechat php test
 */

//define your token
define("TOKEN", "fangzhenyi");
$wechatObj = new wechatCallbackapiTest();
if (isset($_GET["echostr"])) {
    $wechatObj->valid();
} else {
    $wechatObj->responseMsg();
}

class wechatCallbackapiTest
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if ($this->checkSignature()) {
            echo $echoStr;
            exit;
        }
    }

    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");
        //extract post data
        if (!empty($postStr)) {
            /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
            the best way is to check the validity of xml by yourself */
            libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;


            $keyword = trim($postObj->Content);
            $time = time();
            $textTpl = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[%s]]></MsgType>
                <Content><![CDATA[%s]]></Content>
                <FuncFlag>0</FuncFlag>
              </xml>";
            $url = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>1359011899</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[]]></Content>
<ArticleCount>1</ArticleCount>
<Articles>
  <item>
    <Title><![CDATA[%s]]></Title>
    <Description><![CDATA[快来看看您的祝福]]></Description>
    <PicUrl><![CDATA[http://7xj8tq.com1.z0.glb.clouddn.com/duola.jpg]]></PicUrl>
    <Url><![CDATA[%s]]></Url>
  </item>
</Articles>
<FuncFlag>0</FuncFlag>
</xml>";


            if ($postObj->Event == "subscribe") {
                $contentStr = "欢迎来到“跟你说晚安”，祝大家新年快乐！快来生成属于你的独一无二的祝福，回复“新年快乐”，获取幸福链接。";
                $msgType = "text";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            }

            //;
            if (!empty($keyword)) {


                $pattern = "/新年快乐/";
                $pattern1 = "/O.+/";
                if ((preg_match($pattern, $keyword, $arr))) {
                    $contentStr = "<a href='http://chloe.sleepan.com/picture/wanan'>点我,生成你的祝福。</a>";
                    $msgType = "text";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;

                } else if (preg_match_all($pattern1, $keyword, $arr)) {
                    include '../DB.php';
                    $sql = "select * from conInfo where conKey='$keyword' limit 1";
                    $myDb = new DB();
                    $array = $myDb->queryOneData($sql);
                    error_log($array);
                    if ($array["id"]) {
                        $resultStr = sprintf($url, $fromUsername, $toUsername, $array["fromUser"] . "，您的新年祝福已经生成。", "http://chloe.sleepan.com/picture/wanan/temp1.php?key=" . $array["conKey"]);
                        echo $resultStr;
                    } else {
                        error_log("匹配到了O");
                        $contentStr = "没有查找到对应的数据，是不是输错了呀。";
                        $msgType = "text";
                        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                        echo $resultStr;
                    }

                } else {
                    $contentStr = "欢迎来到“跟你说晚安”，祝大家新年快乐！快来生成属于你的独一无二的祝福，回复“新年快乐”，获取幸福链接。";
                    $msgType = "text";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
                }


            } else {
                echo "Input something...";
            }

        } else {
            echo "";
            exit;
        }
    }

    private function checkSignature()
    {
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }

        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }
}

?>